<?php
namespace app\common\controller;
//use think\Controller;
//extends Controller{
class Api{
	protected $data = [];
	public $api_info = false;
	public function __construct() {
		//获取返回的类型  默认html
		$param = IS_GET ? $_GET : $_POST;
		if ($param) {
			foreach ($param as $k => $v) {
				if (in_array($k, ['password', 'old_password'])) {
					$v = strtolower($v);
				}
				$this->$k = $v;
			}
			unset($param);
		}
        if(!is_numeric($this->user_id)){
            $this->user_id = $this->user_id ? decrypt_id($this->user_id) : 0; 
        }
        if(!$this->api){
            $this->api = $this->service ?: '';
        }
		$_GET = $_POST = $this->data;
		$GLOBALS['format'] = $this->data['format'] ? $this->data['format'] : 'json';
		$this->_initialize();

	}
	protected function _initialize() {}

	public function __get($name) {
		return $this->data[$name];
	}
	public function __set($name, $value) {
		$this->data[$name] = $value;
	}

	/**
	 * @name 检测请求的api来源
	 * @access protected
	 * @param boolean $get 是否获得单个stream信息
	 * @param array $must 必须的参数
	 * @param string $method 请求方式  默认不限制
	 * @return boolean|array|object  返回信息
	 */
	protected function checkApi($must = [], $method = '') {
		if ($method) {
			$method = (strtolower($method) == 'get') ? (IS_GET ? true : false):(IS_POST ? true : false);
			if (!$method) {
				$this->api_info = getApiErrorCode('00100');
				return false;
			}
		}
        if(session('is_admin') !== true){
            $authModel = model('open/UserAuth');
            $uid = $authModel->checkAuthForApi($this->ak);
    		if ($uid === false) {
    			$this->uid = 0;
    			$this->api_info = getApiErrorCode('00500');
    			return false;
    		} else {
    			$this->uid = $uid;
    		}
        }else{
            $this->uid = decrypt_id(session('aid'));
        }
		
        
		if (!empty($must)) {
			$m_count = count($must);
			$r_count = count(array_intersect_key(array_flip($must), $this->data));
			if ($m_count > $r_count) {
				$this->api_info = getApiErrorCode('40001');
				return false;
			}
		}
        
		return true;

	}

	/**
	 * @name 调用服务发送请求操作
	 * @param string $type 请求的类型   [post,put,get,delete]
	 * @param array $params 请求时携带的参数
	 * @param string $url  请求的url
	 * @return array 请求后的返回数据
	 */
	protected function request($type = '', $params = [], $url = '') {
		if (!$type || !$url) {
			return [];
		}

		//加载httpful
		vendor('Bootstrap', VENDOR_PATH . 'Httpful' . DS);
		//初始化
		\Httpful\Bootstrap::init();
		//参数拼接
		if (in_array($type, ['get', 'delete'])) {
			$url .= '?' . http_build_query($params);
			$send = \Httpful\Request::$type($url);
		} else {
			$send = \Httpful\Request::$type($url)
				->sendsForm()
				->body($params);
		}
        if(is_array($this->header) && $this->header){
    		foreach ($this->header as $key => $val) {
    			$send = $send->$key($val);
    		}
        }
		$response = $send
			->expectsHtml()
			->send();
		//数据转换为数组返回
		return object2array($response->body);
	}
}
